/*
 * Created by SharpDevelop.
 * User: tjog
 * Date: 10/10/2009
 * Time: 9:09 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using WeifenLuo.WinFormsUI.Docking;
using test;


public partial class DataViewForm : System.Windows.Forms.Form
{
	private System.Windows.Forms.MainMenu mainMenu;
	private System.Windows.Forms.MenuItem fileMenu;
	//private System.Windows.Forms.MenuItem exitFileMenu;
	private System.Windows.Forms.DataGrid dataGrid;
	private DataProject project;
	//private DecDataGridView gridView;// = new DataGridView();
	private StatusStrip statusStrip;
	private ToolStripProgressBar toolStripProgressBar;
	private ToolStripStatusLabel toolStripStatusLabel;
	private ContextMenuStrip colHeaderContextMenuStrip;
	
	private bool saveLayout = true;
	private readonly DockPanel dockPanel;
	
	public DataViewForm()
	{
		InitializeComponent();
		
		this.IsMdiContainer = true; // need this
		
		this.dockPanel = new DockPanel();
		this.dockPanel.ActiveAutoHideContent = null;
		this.dockPanel.Dock = DockStyle.Fill;
		this.dockPanel.Name = "dockPanel";
		this.Controls.Add(dockPanel);
		this.dockPanel.BringToFront();
		
		//this.dockPanel.Controls.Add(gridView);
		//this.Controls.Add(gridView);

	}
	
	private void InitializeComponent() {
		
		//FlowLayoutPanel flowLayout = new FlowLayoutPanel();
		//flowLayout.FlowDirection = FlowDirection.TopDown;
		//flowLayout.Dock = DockStyle.Fill;
		//this.Controls.Add(flowLayout);
		
		this.project = new DataProject();
		//this.dataGrid = new DataGrid();
		//this.gridView = new test.DecDataGridView();
		//this.gridView.Dock = DockStyle.Fill;

		initMenu();
		
		//this.AutoScaleBaseSize = new System.Drawing.Size(5, 3);
		this.ClientSize = new System.Drawing.Size( 300, 200);

		this.Name = "testStdfFile";
		this.Text = "testStdfFile";
		CenterToScreen();
		
		
		//flowLayout.Controls.Add(this.gridView);

		//this.Controls.
		//this.gridView.Name = "GridView";
		
		this.statusStrip = new System.Windows.Forms.StatusStrip();
		this.statusStrip.Location = new System.Drawing.Point( 0, 251);
		this.statusStrip.TabIndex = 0;
		this.statusStrip.Name = "statusStrip";
		this.statusStrip.Text = "statusStrip";
		this.Controls.Add(this.statusStrip);
		this.toolStripProgressBar = new ToolStripProgressBar();
		toolStripProgressBar.Enabled = false;
		this.toolStripStatusLabel = new ToolStripStatusLabel();
		this.statusStrip.Items.Add(this.toolStripProgressBar);
		this.statusStrip.Items.Add(this.toolStripStatusLabel);
		
		this.colHeaderContextMenuStrip = new ContextMenuStrip();
		this.colHeaderContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(cms_Opening);
	}
	private void initMenu()
	{
		this.mainMenu = new MainMenu();
		this.fileMenu = new MenuItem("&File");
		MenuItem openFileMenu = new MenuItem("&Open");
		MenuItem exitFileMenu = new MenuItem("E&xit");
		
		this.mainMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.fileMenu });
		this.fileMenu.Index = 0;
		MenuItem menuSeparator = new MenuItem("-");
		this.fileMenu.MenuItems.Add(openFileMenu);
		this.fileMenu.MenuItems.Add(menuSeparator);
		this.fileMenu.MenuItems.Add(exitFileMenu);
		//this.fileMenu.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { this.exitFileMenu });
	
		exitFileMenu.Click += new System.EventHandler(this.exitFileMenu_Click);
		openFileMenu.Click += new System.EventHandler(this.openFileMenu_Click);
		this.Menu = this.mainMenu;
	}
	
	[STAThread]
	public static void Main()
	{
		Application.EnableVisualStyles();
		Application.Run(new DataViewForm());
	}
	private void exitFileMenu_Click(object sender, System.EventArgs e)
	{
		Application.Exit();
	}
	private void openFileMenu_Click(object sender, System.EventArgs e)
	{
		OpenFileDialog dlg = new OpenFileDialog();
		dlg.Filter = "STDF Files (*.stdf;*.std_1)|*.stdf;*.std_1|All files (*.*)|*.*";
		dlg.Title = "Select a Data file";
		dlg.DefaultExt = "std_1";
		if(dlg.ShowDialog() == DialogResult.OK) {
			// Do something
			string fileName = dlg.FileName;
			string fileExt  = System.IO.Path.GetExtension(fileName);

            int initialDataTableCount = this.project.dataSet.Tables.Count;
			
			//
			// If file extenstion is a supported extension then
			// * Create a new DataTable
			// * Load the data from the file into the new DataTable
			// * Add the new DataTable to the project dataset
			//
			bool newDataFile = false;
			//if(fileExt == "*.stdf" || fileExt == "*.std_1") {
				// Create a new table and add to project
				{
                                
                    STDFOpenDialog optionsDialog = new STDFOpenDialog();
                    optionsDialog.fileTextBox.Text = fileName;
                    DialogResult res = optionsDialog.ShowDialog();

                    if (res == DialogResult.OK)
                    {
                        DataTable newTable = new DataTable(fileName);
                        DataTable newHeaderTable = new DataTable("Properties_" + fileName);

                        //test.DataFileReader.loadSTDF(fileName, ref newTable, ref newHeaderTable);
                        bool success = false;
                        stdf.StdfFile stdfFile = new stdf.StdfFile();
                        
                        stdfFile.loadMIR = optionsDialog.cbMIR.Checked;
                        stdfFile.loadSDR = optionsDialog.cbSDR.Checked;
                        stdfFile.loadWIR = optionsDialog.cbWIR.Checked;
                        stdfFile.loadPRR = optionsDialog.cbPRR.Checked;
                        //stdfFile.loadPRR = true;
                        stdfFile.loadPTR = optionsDialog.cbPTR.Checked;
                        stdfFile.loadFTR = optionsDialog.cbFTR.Checked;
                        stdfFile.ignoreAlarm = optionsDialog.cbIgnoreAlarms.Checked;

                        success = stdfFile.open(fileName, stdf.RWMode.ReadOnly);
                        if (success)
                        {
                            success = stdfFile.read(ref newTable, ref newHeaderTable);
                        }

                        this.project.dataSet.Tables.Add(newHeaderTable);
                        this.project.dataSet.Tables.Add(newTable);
                        newDataFile = true;
                        newTable.TableName = System.IO.Path.GetFileName(fileName);
                        newHeaderTable.TableName = "Properties_" + fileName;
                    }
				}
			//}
						

			
			//if(newDataFile == true && this.project.dataSet.Tables.Count > 0) {
            if(this.project.dataSet.Tables.Count > initialDataTableCount) {
                for (int i = initialDataTableCount; i < this.project.dataSet.Tables.Count; i++)
                {
                    DataTable newTable = this.project.dataSet.Tables[i];

                    DecDataGridDockContent content1 = new test.DecDataGridDockContent();
                    content1.Name = newTable.TableName;
                    content1.TabText = content1.Name;

                    content1.Show(this.dockPanel);

                    createDataGridView(ref content1.gridView, ref newTable);
                }
			}

		}
	}
	private void createDataGridView(ref DecDataGridView gv, ref DataTable newTable) {
		/// Assign DataTable to DataGridView		
			gv.DataSource = newTable;
			
			/// Set DataGridView headers
			foreach (DataColumn dc in newTable.Columns) {
				gv.Columns[dc.ColumnName].HeaderText = dc.Caption;
			}
			/// Resize the DataGridView columns to fit the newly loaded content
			gv.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCells);
			//PrintTable(newTable);
			
			gv.AllowUserToOrderColumns = true;
			gv.AllowUserToAddRows = false;
			gv.ReadOnly = true;
			//this.gridView.RowsDefaultCellStyle.BackColor = Color.Bisque;
			gv.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
			foreach (DataGridViewColumn gridViewColumn in gv.Columns) {
				gridViewColumn.HeaderCell.ContextMenuStrip = colHeaderContextMenuStrip;
			}
		
	}
	private void dgView_MouseClick( object sender, DataGridViewCellMouseEventArgs e)
	{
		if(e.Button == MouseButtons.Right) {
			
		}
	}
	// This event handler is invoked when the ContextMenuStrip
    // control's Opening event is raised. It demonstrates
    // dynamic item addition and dynamic SourceControl 
    // determination with reuse.
    void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
    {
        // Acquire references to the owning control and item.
        Control c = colHeaderContextMenuStrip.SourceControl as Control;
        ToolStripDropDownItem tsi = colHeaderContextMenuStrip.OwnerItem as ToolStripDropDownItem;

        // Clear the ContextMenuStrip control's Items collection.
        colHeaderContextMenuStrip.Items.Clear();

        // Check the source control first.
        if (c != null)
        {
            // Add custom item (Form)
            colHeaderContextMenuStrip.Items.Add("Source: " + c.GetType().ToString());
        }
        else if (tsi != null)
        {
            // Add custom item (ToolStripDropDownButton or ToolStripMenuItem)
            colHeaderContextMenuStrip.Items.Add("Source: " + tsi.GetType().ToString());
        }

        // Populate the ContextMenuStrip control with its default items.
        colHeaderContextMenuStrip.Items.Add("-");
        colHeaderContextMenuStrip.Items.Add("Show Properties");
        colHeaderContextMenuStrip.Items.Add("Set Order");

        //colHeaderContextMenuStrip.Items["Show Properties"].Click += new EventHandler(this.toolStripShowProperties_Click);

        // Set Cancel to false. 
        // It is optimized to true based on empty entry.
        e.Cancel = false;
    }
    private static void PrintTable(DataTable dt) {
        DataTableReader dtReader = dt.CreateDataReader();
        while (dtReader.Read()) {
            for (int i = 0; i < dtReader.FieldCount; i++) {
                Console.Write("{0} = {1} ",
                    dtReader.GetName(i).Trim(),
                    dtReader.GetValue(i).ToString().Trim());
            }
            Console.WriteLine();
        }
        dtReader.Close();
    }

    // 
    private void toolStripShowProperties_Click(object sender, EventArgs args)
    {
        //dataGridView.Rows[mouseLocation.RowIndex].Cells[mouseLocation.ColumnIndex].Style.BackColor = Color.Red;
    }

}